package tree.medium;

import com.sun.jmx.remote.internal.ArrayQueue;
import tree.TreeNode;

import java.util.*;

/**
 * 二叉树的锯齿形层序遍历
 */
public class BinaryTreeZigzagLevelOrderTraversal_103 {

    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> list = new ArrayList<>();
        if (root == null) {
            return list;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        boolean flag = false;
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> li = new ArrayList<>();
            while(size-- > 0) {
                TreeNode poll = queue.poll();
                if (!flag) {
                    li.add(poll.val);
                } else {
                    li.add(0, poll.val);
                }
                if (poll.left != null) {
                    queue.offer(poll.left);
                }
                if (poll.right != null) {
                    queue.offer(poll.right);
                }
            }
            list.add(li);
            flag = !flag;
        }
        return list;
    }

}
